//
//  ComboViewController.m
//  MeterMart
//
//  Created by ENERGY on 2018/11/4.
//  Copyright © 2018年 ENERGY. All rights reserved.
//

#import "ComboViewController.h"
#import "SDCycleScrollView.h"
#import "ComboCollectionViewCell.h"
#import <WebKit/WebKit.h>
#import "ConfirmComboViewController.h"
#import "WeChatLoginViewController.h"
@interface ComboViewController ()<UITableViewDelegate, UITableViewDataSource, UINavigationControllerDelegate, SDCycleScrollViewDelegate, UICollectionViewDelegate, UICollectionViewDataSource, WKNavigationDelegate>
@property (nonatomic, strong)UITableView * tableView;
@property (nonatomic, strong)UIView * headerView;
@property (nonatomic, strong)SDCycleScrollView *cycleScrollView;
@property (nonatomic, strong)UICollectionView * collectionView;
@property (nonatomic, strong)UILabel * moneyLab;//金额
@property (nonatomic, strong)WKWebView * webView;
@property (nonatomic, assign)int webH;//web页的高度
@property (nonatomic, strong)NSDictionary * model;
@property (nonatomic, strong)NSMutableArray * itemArr;
@property (nonatomic, assign)int cellRow;
@property (nonatomic, strong)UIView * bottomBorderLine;
@property (nonatomic, strong)UIView * bottomBar;
@property (nonatomic, strong)NSString * typeID;//商品类型，1级分类
@property (nonatomic, strong)NSString * phoneString;
@property (nonatomic, strong)NSString * tokenString;
@property (nonatomic, assign)int presentTimes;//是否为modal回来后出来的页面
@property (nonatomic, strong)UIButton * orderBtn;//预定按钮
- (void)ifLogin;
@end

@implementation ComboViewController(networking)
- (void)getProduceInfo{
    int liveDays = [self.dayString intValue];
    NSDictionary * dic = @{
                           @"id":self.prodeceID,
                           @"goodssum":@(liveDays),
                           @"token":self.tokenString,
                           @"phone":self.phoneString
                           };
    [self showprogressHUD];
    [[AFAppDotNetAPIClient sharedClient] POST:@"detailsiosapi/hotel_deatil" parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self hiddenProgressHUD];
        if ([responseObject[@"sign"] isEqualToString:@"1"]) {
            self.model = responseObject[@"list"];
        }else if ([[NSString stringWithFormat:@"%@", responseObject[@"sign"]] isEqualToString:@"400"]) {
            ShowMessage(responseObject[@"msg"]);
            [self ifLogin];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self hiddenProgressHUD];
        [self showError:error];
    }];
}

@end
@implementation ComboViewController
- (UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleDefault;
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if ([[UserModel sharedInstanced].token isEqualToString:@""] || [UserModel sharedInstanced].token == nil || [[UserModel sharedInstanced].token length] == 0 || [[UserModel sharedInstanced].mobile isEqualToString:@""] || [UserModel sharedInstanced].mobile == nil || [[UserModel sharedInstanced].mobile length] == 0) {
        self.tokenString = @"";
        self.phoneString = @"";
        WeChatLoginViewController * vc = [[WeChatLoginViewController alloc] init];
        UINavigationController* navi = [[UINavigationController alloc] initWithRootViewController:vc];
        if (self.presentTimes == 0) {
            self.presentTimes ++;
            [self.navigationController presentViewController:navi animated:YES completion:nil];
        }else{
            [vc.navigationController dismissViewControllerAnimated:YES completion:nil];
            [self.tabBarController setSelectedIndex:0];
            [self.navigationController popToRootViewControllerAnimated:YES];
        }return;
    }else{
        self.tokenString = [UserModel sharedInstanced].token;
        self.phoneString = [UserModel sharedInstanced].mobile;
    }
    [self setUpBottomBar];
    [self.view addSubview:self.tableView];
    [self getProduceInfo];//网络接口
}
- (void)viewDidLoad {
    [super viewDidLoad];
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    self.view.backgroundColor = [UIColor whiteColor];
}
#pragma mark - init
- (NSMutableArray *)itemArr{
    if (!_itemArr) {
        _itemArr = @[].mutableCopy;
    }return _itemArr;
}
- (void)setModel:(NSDictionary *)model{
    _model = model;
    self.cycleScrollView.imageURLStringsGroup = [model[@"info"] objectForKey:@"goodsimg"];
    self.moneyLab.text = [NSString stringWithFormat:@"￥%@", model[@"totalmoney"]];    
    [self.itemArr addObjectsFromArray:[model[@"info"] objectForKey:@"attributes_name"]];
    if ((int)self.itemArr.count%2 > 0) {
        self.cellRow = (int)self.itemArr.count/2 + 1;
    }else{
        self.cellRow = (int)self.itemArr.count/2;
    }
    self.collectionView.frame = CGRectMake(0, self.cycleScrollView.bottom + 41/WIDTH_6_SCALE, SCREEN_WIDTH, 28/WIDTH_6_SCALE * self.cellRow);
    self.bottomBorderLine.frame = CGRectMake(0, self.collectionView.bottom, SCREEN_WIDTH, 1/WIDTH_6_SCALE);
    
    if ([model[@"info"] objectForKey:@"goodsdetails"] == nil || [[model[@"info"] objectForKey:@"goodsdetails"] length] == 0 || [[model[@"info"] objectForKey:@"goodsdetails"] isEqualToString:@""]) {
        
    }else{
        [self showprogressHUD];
        [self.webView loadHTMLString:[model[@"info"] objectForKey:@"goodsdetails"] baseURL:nil];
    }
    self.typeID = [model[@"info"] objectForKey:@"typeid"];
    [self.collectionView reloadData];
}
- (void)setUpBottomBar{
    UIView * bottomBar = [[UIView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT - BOTTOM_HEIGHT - 49/WIDTH_6_SCALE - NAVI_HEIGHT, SCREEN_WIDTH, 49/WIDTH_6_SCALE)];
    bottomBar.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:bottomBar];
    self.bottomBar = bottomBar;
    //金额
    self.moneyLab = [[UILabel alloc] initWithFrame:CGRectMake(18/WIDTH_6_SCALE, 0, SCREEN_WIDTH/2 - 18/WIDTH_6_SCALE, bottomBar.height)];
    [self label:self.moneyLab withFont:DEF_FontSize_16 withText:@"￥--" withTextColor:getColor(mainRedColor) withTextAlignment:NSTextAlignmentLeft withView:bottomBar];
    //预定按钮
    UIButton * orderBtn = [[UIButton alloc] initWithFrame:CGRectMake(self.moneyLab.right, self.moneyLab.top, SCREEN_WIDTH/2, self.moneyLab.height)];
    self.orderBtn = orderBtn;
    [self button:orderBtn withBGColor:getColor(mainRedColor) withLayerBorderColor:nil withLayerBorderWith:0 withCornerRadius:0 withMasksToBounds:NO withViwe:bottomBar];
    [orderBtn setTitle:@"预定" forState:UIControlStateNormal];
    [orderBtn addTarget:self action:@selector(orderBtnClick) forControlEvents:UIControlEventTouchUpInside];
    orderBtn.titleLabel.font = DEF_FontSize_14;
    [orderBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    if ([self.isHotel isEqualToString:@"1"] && [self.roomCount isEqualToString:@"0"]) {
        orderBtn.userInteractionEnabled = NO;
        [orderBtn setBackgroundColor:[UIColor grayColor]];
    }else{
        orderBtn.userInteractionEnabled = YES;
        [orderBtn setBackgroundColor:getColor(mainRedColor)];
    }
}
- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - BOTTOM_HEIGHT - 49/WIDTH_6_SCALE - NAVI_HEIGHT) style:UITableViewStylePlain];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = [UIColor whiteColor];
        _tableView.tableHeaderView = self.headerView;
    }return _tableView;
}
- (UIView *)headerView{
    if (!_headerView) {
        _headerView = [[UIView alloc] init];
        self.cycleScrollView = [[SDCycleScrollView alloc] init];
        if (Is_Iphone_X) {
            _headerView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - BOTTOM_HEIGHT - 49/WIDTH_6_SCALE);
            self.cycleScrollView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 251/WIDTH_6_SCALE + 24);
        }else{
            _headerView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - BOTTOM_HEIGHT - 49/WIDTH_6_SCALE);
            self.cycleScrollView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 251/WIDTH_6_SCALE);
        }
        _headerView.backgroundColor = [UIColor whiteColor];
        //轮播图
        self.cycleScrollView.placeholderImage = [UIImage imageNamed:@"YimiPlaceHolder"];
        self.cycleScrollView.delegate = self;
        self.cycleScrollView.pageControlAliment = SDCycleScrollViewPageContolAlimentCenter;
        self.cycleScrollView.currentPageDotColor = [UIColor whiteColor];
        self.cycleScrollView.bannerImageViewContentMode = UIViewContentModeScaleToFill;
        self.cycleScrollView.pageControlAliment = SDCycleScrollViewPageContolAlimentCenter;
        [_headerView addSubview:self.cycleScrollView];
        //详情
        UIImageView * detailImg = [[UIImageView alloc] initWithFrame:CGRectMake(19/WIDTH_6_SCALE, self.cycleScrollView.bottom + 17/WIDTH_6_SCALE, 12/WIDTH_6_SCALE, 14/WIDTH_6_SCALE)];
        detailImg.image = [UIImage imageNamed:@"hotel"];
        [_headerView addSubview:detailImg];
        UILabel * detailLab = [[UILabel alloc] initWithFrame:CGRectMake(detailImg.right + 11/WIDTH_6_SCALE, 0, 100/WIDTH_6_SCALE, 15/WIDTH_6_SCALE)];
        detailLab.centerY = detailImg.centerY;
        [self label:detailLab withFont:DEF_FontSize_15 withText:@"详细信息" withTextColor:[UIColor blackColor] withTextAlignment:NSTextAlignmentLeft withView:_headerView];
        //collectionView
        UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc] init];
        layout.itemSize = CGSizeMake(SCREEN_WIDTH/2, 28/WIDTH_6_SCALE);
        // 设置 最小列间距
        layout.minimumInteritemSpacing  = 0/WIDTH_6_SCALE;
        layout.minimumLineSpacing = 0/WIDTH_6_SCALE;
        self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, self.cycleScrollView.bottom + 41/WIDTH_6_SCALE, SCREEN_WIDTH, 164/WIDTH_6_SCALE) collectionViewLayout:layout];
        self.collectionView.backgroundColor = [UIColor whiteColor];
        self.collectionView.delegate = self;
        self.collectionView.dataSource = self;
        [self.collectionView registerClass:[ComboCollectionViewCell class] forCellWithReuseIdentifier:NSStringFromClass([ComboCollectionViewCell class])];
        [_headerView addSubview:self.collectionView];
        //分割线
        UIView * bottomBorderLine = [[UIView alloc] initWithFrame:CGRectMake(0, self.collectionView.bottom, SCREEN_WIDTH, 1/WIDTH_6_SCALE)];
        bottomBorderLine.backgroundColor = getColor(@"f7f7fb");
        self.bottomBorderLine = bottomBorderLine;
        [_headerView addSubview:bottomBorderLine];
        //首先是关键JS代码：
        NSString *jScript =
        @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta); var imgs = document.getElementsByTagName('img');for (var i in imgs){imgs[i].style.maxWidth='100%';imgs[i].style.height='auto';}";
        //然后初始化并加入JS片段：
        WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:jScript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
        WKUserContentController *wkUController = [[WKUserContentController alloc] init];
        [wkUController addUserScript:wkUScript];
        WKWebViewConfiguration *wkWebConfig = [[WKWebViewConfiguration alloc] init];
        wkWebConfig.userContentController = wkUController;
        self.webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, bottomBorderLine.bottom, SCREEN_WIDTH, 100) configuration:wkWebConfig];
        self.webView.scrollView.bounces = NO;
        self.webView.scrollView.showsHorizontalScrollIndicator = NO;
        self.webView.scrollView.scrollEnabled = NO;
        self.webView.navigationDelegate = self;
        [_headerView addSubview:self.webView];
    }return _headerView;
}
#pragma mark - WKWebViewDelegeta
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    WS(ws)
    [webView evaluateJavaScript:@"document.body.offsetHeight;" completionHandler:^(id _Nullable any, NSError * _Nullable error) {
        [self hiddenProgressHUD];
        NSString *heightStr = [NSString stringWithFormat:@"%@",any];
        ws.webH = [heightStr intValue];
        self.webView.frame = CGRectMake(0, self.bottomBorderLine.bottom, SCREEN_WIDTH, ws.webH + 20);
        self.headerView.frame = CGRectMake(0, 0, SCREEN_WIDTH, self.webView.bottom);
        self.tableView.tableHeaderView = self.headerView;
        [self hiddenProgressHUD];
        [self.tableView reloadData];
    }];
}
#pragma mark - collectionViewDelegate和collectionViewDatasource
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    ComboCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([ComboCollectionViewCell class]) forIndexPath:indexPath];
    cell.model = self.itemArr[indexPath.row];
    return cell;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.itemArr.count;
}
#pragma mark - action
- (void)orderBtnClick{
    if ([self.phoneString isEqualToString:@""] || [self.phoneString length] == 0 || self.phoneString == nil || [self.tokenString isEqualToString:@""] || [self.tokenString length] == 0 || self.tokenString == nil) {
        self.orderBtn.userInteractionEnabled = NO;
        [self.orderBtn setBackgroundColor:[UIColor grayColor]];
    }
    ConfirmComboViewController * vc = [[ConfirmComboViewController alloc] init];
    vc.produceID = self.prodeceID;
    vc.startTimeString = self.startTimeString;
    vc.endTimeString = self.endTimeString;
    vc.dayString = self.dayString;
    vc.typeID = self.typeID;
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)ifLogin{
    WeChatLoginViewController * vc = [[WeChatLoginViewController alloc] init];
    UINavigationController* navi = [[UINavigationController alloc] initWithRootViewController:vc];
    vc.backHomePageBlock = ^{
        [vc dismissViewControllerAnimated:YES completion:nil];
        [self.tabBarController setSelectedIndex:0];
        [self.navigationController popToRootViewControllerAnimated:YES];
    };
    [self presentViewController:navi animated:YES completion:nil];
}
@end
